package com.ycz.springcloud.config;/*
 @author ycz
 @date 2021-07-30-23:42  
*/


import com.ycz.springcloud.domain.SysUser;
import com.ycz.springcloud.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


//自定义的UserRealm    extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权功能");
        //授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        SysUser currentUser = (SysUser) subject.getPrincipal();//获取下面的 user
        //增加user:add的授权功能
       // info.addStringPermission("user:add");
       // info.addStringPermission(currentUser.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证功能");

        UsernamePasswordToken userToken=(UsernamePasswordToken) authenticationToken;
        SysUser sysUser=sysUserService.queryUserByName(userToken.getUsername());
        if (sysUser==null){
            return null; //抛出异常 ，UnknownAccountException
        }

        Subject currentSubject=SecurityUtils.getSubject();
        Session session=currentSubject.getSession();
        session.setAttribute("loginName",sysUser.getLoginName());
        session.setAttribute("role","admin");
                                            //传值user到上面
        return new SimpleAuthenticationInfo(sysUser,sysUser.getLoginPassword(),sysUser.getRealname());
    }
}
